<?php

class User extends Controller
{
    
    public function __construct()
    {
        parent::__construct();
        Session::init();
        $logged = Session::get('log_in');
        
        $role = Session::get('role');
                                    
        if($logged === false || $role != ADMIN)
        {
            Session::destroy();
            header('location: ../login');
            exit;
        }
        
    }
    
    
    public function index()
    {
        $res = $this->model->userList();
        
        if($res) 
        {
            $this->view->user_list = $res;
            $this->view->render('user/index');   
        } else {
            die('somsing wrong : user controller');
        }   
    }
    
    
    public function create()
    {
        $data = array(
            'login' => $_POST['login'],
            'password' => $_POST['password'],
            'role' => $_POST['role'],
        
        ); 
        $this->model->create($data);
        header('location: ' . URL . 'user');
    }
    
    /**
    * edit
    * 
    */
    public function edit($id)
    {
        $this->view->user = $this->model->listUserById($id);
        $this->view->render('user/edit');
        exit();
    }
    
    
    /**
    * edit save
    * 
    */
    public function editSave()
    {
       $data = array(
            'id'        => $_POST['id'],
            'login'     => $_POST['login'],
            'password'  => $_POST['password'],
            'role'      => $_POST['role'],
        
        ); 
        $this->model->editSave($data);
        header('location: ' . URL . 'user');
    }
    
    /**
    * delete user
    * 
    * @param mixed $id
    */
    public function delete($id)
    {
        $res = $this->model->delete($id);
        //@todo: error messsage
        header('location: ' . URL . 'user');
    }
    
}